package com.example.oauth2.service;

import com.example.oauth2.entry.Client;
import com.example.oauth2.repository.ClientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 自定义ClientDetailsService类
 */
@Component
public class CustomClientDetailsService implements ClientDetailsService {

    @Autowired
    private ClientRepository clientRepository;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {

        Optional<Client> clientOptional = Optional.ofNullable(clientRepository.findByClientId(clientId));

        if (clientOptional.isPresent()) {
            return new CustomClientDetails(clientOptional.get());
        }

        throw new ClientRegistrationException(clientId);
    }
}
